package com.example.wan1.view.setting;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.wan1.R;
import com.example.wan1.adapter.ItemAdapter;
import com.example.wan1.adapter.ThemeAdapter;
import com.example.wan1.bus.RxBus;
import com.example.wan1.data.IsNotObserver;
import com.example.wan1.data.RetrofitUtil;
import com.example.wan1.data.RxSchedulers;
import com.example.wan1.data.cookie.CookieManager;
import com.example.wan1.model.ItemBean;
import com.example.wan1.utils.AppUtils;
import com.example.wan1.utils.ColorTheme;
import com.example.wan1.utils.SPUtils;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.MainActivity;
import com.example.wan1.view.about.AboutUsActivity;
import com.example.wan1.view.login.UserManager;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SwitchCompat;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dagger.android.support.DaggerDialogFragment;

import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;

/***
 * 创建时间：2020/8/2 8:51
 * 创建人：10850
 * 功能描述：设置
 * 这里需要保存状态，一些按钮的状态，需要储存下来
 */
public class SettingDialogFragment extends DaggerDialogFragment {

    @BindView(R.id.setting_rv)
    RecyclerView mSettingRv;
    @BindView(R.id.setting_tabr)
    Toolbar mToolbar;
    @BindView(R.id.theme_group)
    RadioGroup mRadioGroup;
    @BindView(R.id.bottom_sheet)
    LinearLayout mBottomSheet;
    @BindView(R.id.theme_rv)
    RecyclerView mThemeRv;

    @Inject
    ThemeAdapter mThemeAdapter;
    @Inject
    List<String> mData;
    @Inject
    ItemAdapter mAdapter;
    @Inject
    List<ItemBean> mList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mToolbar.setBackgroundColor(ToolsUtils.getAttrValue(getActivity()));
        ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(v -> dismiss());
        //mAdapter = new ItemAdapter(R.layout.mine_item, mList);
        mSettingRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mSettingRv.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
            String title = mList.get(i).getTitle();
            if (!title.equals("主题设置")) {
                mBottomSheet.setVisibility(View.GONE);
            }

            if (mList.get(i).getType() == 1 || mList.get(i).getType() == 3) {
                if ("清除缓存".equals(title)) {
                    final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                    dialog.setIcon(R.mipmap.ic_launcher)
                            .setTitle("温馨提示")
                            .setMessage("确定清除缓存吗？")
                            .setCancelable(true)
                            .setPositiveButton("清除",
                                    (dialog1, which) -> {
                                        DataCleanManager.clearAllCache(getActivity());
                                        //不光要清除缓存，而且还要更改目前的缓存数量
                                        mAdapter.notifyDataSetChanged();
                                    })
                            .setNegativeButton("取消",
                                    (dialog12, which) -> dialog12.dismiss());
                    dialog.show();
                }
            }
            if (title.equals("夜间模式")) {
                //这里弹出底部的对话框，选择三个模式
                // 底部弹出对话框
                Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
                View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_setting_night, null);
                bottomDialog.setContentView(contentView);
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
                params.width = getResources().getDisplayMetrics().widthPixels - ToolsUtils.dp2px(16);
                params.bottomMargin = ToolsUtils.dp2px(8);
                contentView.setLayoutParams(params);
                bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
                bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
                bottomDialog.show();
                contentView.findViewById(R.id.night1).setOnClickListener(v -> {
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
                    SPUtils.put(getActivity(), "night_mode_open", true);
                    SPUtils.put(getActivity(), "night_mode_id", MODE_NIGHT_YES);
                    //RxBus.getDefault().postSticky(new NotifyOperateEvent("OpenMode"));
                    mAdapter.notifyItemChanged(i);
                    bottomDialog.dismiss();
                });

                contentView.findViewById(R.id.night2).setOnClickListener(v -> {
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
                    SPUtils.put(getActivity(), "night_mode_open", false);
                    SPUtils.put(getActivity(), "night_mode_id", MODE_NIGHT_NO);
                    //RxBus.getDefault().postSticky(new NotifyOperateEvent("CloseMode"));
                    mAdapter.notifyItemChanged(i);
                    bottomDialog.dismiss();
                });

                contentView.findViewById(R.id.night3).setOnClickListener(v -> {
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
                    SPUtils.put(getActivity(), "night_mode_open", true);
                    SPUtils.put(getActivity(), "night_mode_id", MODE_NIGHT_AUTO_BATTERY);
                    //RxBus.getDefault().postSticky(new NotifyOperateEvent("OpenMode"));
                    mAdapter.notifyItemChanged(i);
                    bottomDialog.dismiss();
                });

                contentView.findViewById(R.id.night4).setOnClickListener(v -> {
                    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
                    SPUtils.put(getActivity(), "night_mode_open", true);
                    SPUtils.put(getActivity(), "night_mode_id", MODE_NIGHT_FOLLOW_SYSTEM);
                    //RxBus.getDefault().postSticky(new NotifyOperateEvent("OpenMode"));
                    mAdapter.notifyItemChanged(i);
                    bottomDialog.dismiss();
                });
            }
            //主题设置
            if (title.equals("主题设置")) {
                //如果是主题设置的话，默认几个颜色style，然后下面部分是一个list颜色表，颜色最好不要重复
                //SPUtils.put(getActivity(), "theme_color", "orange");

                /*ColorTheme newTheme = new ColorTheme((AppCompatActivity) getActivity());
                newTheme.updateTheme(R.style.YellowTheme);
                dismiss();*/

                mBottomSheet.setVisibility(View.VISIBLE);
            } else if (title.equals("退出登录")) {
                new Thread(() -> RetrofitUtil.getInstance().loginOut()
                        .compose(RxSchedulers.observableIO2Main())
                        .subscribe(new IsNotObserver() {
                            @Override
                            public void onSuccess(int code, String result) {
                                Log.i("zxd", "onSuccess: loginout");
                                //退出成功
                                UserManager.getInstance().delete();
                                //AppUtils.setIsLogin(false);
                                //SPUtils.remove(getActivity(), "user_info");
                                CookieManager.getInstance().clearAllCookie();
                                RetrofitUtil.noCookie();
                                RxBus.getDefault().post("theme");
                                dismiss();
                            }

                            @Override
                            public void onFailure(Throwable e, String errorMsg) {
                                ToastUtils.showToast(e.getMessage());
                            }
                        })).start();
            } else if (title.equals("关于我们")) {
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
            }
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view12, i) -> {
            String title = mList.get(i).getTitle();
            switch (view12.getId()) {
                case R.id.mine_item_toggle:
                    if (title.equals("导航栏着色")) {
                        SwitchCompat switchCompat = view12.findViewById(R.id.mine_item_toggle);
                        /*if (switchCompat.isChecked())
                            SPUtils.put(getActivity(), "navigation_bar_color", true);
                        else
                            SPUtils.put(getActivity(), "navigation_bar_color", false);
                        dismiss();
                        startActivity(new Intent(getActivity(), MainActivity.class));*/
                        //这里不跳转到首页了，直接修改试试行不行
                        Window window = getActivity().getWindow();
                        Window window1 = getDialog().getWindow();
                        if (switchCompat.isChecked()) {
                            SPUtils.put(getActivity(), "navigation_bar_color", true);
                            if (ToolsUtils.getThemeColor(getActivity()) != 0) {
                                window.setNavigationBarColor(ToolsUtils.getThemeColor(getActivity()));
                                window1.setNavigationBarColor(ToolsUtils.getThemeColor(getActivity()));
                            } else {
                                window.setNavigationBarColor(ToolsUtils.getAttrValue(getActivity()));
                                window1.setNavigationBarColor(ToolsUtils.getAttrValue(getActivity()));
                            }
                            if (ToolsUtils.getThemeColor(getActivity()) != 0)
                                switchCompat.setThumbTintList(ColorStateList.valueOf(ToolsUtils.getThemeColor(getActivity())));
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                switchCompat.setThumbTintList(ColorStateList.valueOf(getContext().getColor(R.color.gray)));
                            }
                            SPUtils.put(getActivity(), "navigation_bar_color", false);
                            window.setNavigationBarColor(Color.BLACK);
                            window1.setNavigationBarColor(Color.BLACK);
                        }
                    }
                    /*if (!mList.get(i).isToggle()) {
                        AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
                        SPUtils.put(getActivity(), "night_mode_open", true);
                        RxBus.getDefault().postSticky(new NotifyOperateEvent("OpenMode"));
                    } else {
                        AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
                        SPUtils.put(getActivity(), "night_mode_open", false);
                        RxBus.getDefault().postSticky(new NotifyOperateEvent("CloseMode"));
                    }*/
                    break;
            }
        });

        //mRadioGroup.check(R.id.theme_green_btn);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //选中的btn
                RadioButton btn = group.findViewById(checkedId);
                ColorTheme newTheme = new ColorTheme((AppCompatActivity) getActivity());
                int mThemeId = R.style.AppTheme;
                switch (checkedId) {
                    case R.id.theme_green_btn:
                        mThemeId = R.style.AppTheme;
                        break;
                    case R.id.theme_yellow_btn:
                        mThemeId = R.style.YellowTheme;
                        break;
                    case R.id.theme_pink_btn:
                        mThemeId = R.style.PinkTheme;
                        break;
                    case R.id.theme_purple_btn:
                        mThemeId = R.style.PurpleTheme;
                        break;
                    case R.id.theme_blue_btn:
                        mThemeId = R.style.BlueTheme;
                        break;
                    case R.id.theme_red_btn:
                        mThemeId = R.style.RedTheme;
                        break;
                    case R.id.theme_black_btn:
                        mThemeId = R.style.BlackTheme;
                        break;
                }
                newTheme.updateTheme(mThemeId);
                dismiss();
                SPUtils.remove(getActivity(), "theme_color");
            }
        });

        //mData = new ArrayList<>();
        mData.add("#FF0000");
        mData.add("#FFFF00");
        mData.add("#00FF00");
        mData.add("#0000FF");
        mData.add("#00FFFF");
        mData.add("#CD7F32");
        mData.add("#A67D3D");
        mData.add("#B87333");
        mData.add("#FF7F00");
        mData.add("#FFA500");
        mData.add("#990033");
        mData.add("#FF6699");
        mData.add("#FF3366");
        mData.add("#FF0066");
        mData.add("#FF99FF");
        mData.add("#FF99CC");
        mData.add("#FFCCFF");
        mData.add("#FF00CC");
        mData.add("#FF66FF");
        mData.add("#FF33FF");
        mData.add("#CC33FF");
        mData.add("#99CCFF");
        mData.add("#00CCFF");
        mData.add("#33CCFF");
        mData.add("#66CCFF");
        mData.add("#FFFFCC");
        mData.add("#FFCC00");
        mData.add("#FFFF99");
        mData.add("#FF6600");
        mData.add("#FF6633");
        mData.add("#FF9933");
        mData.add("#CC3333");
        mData.add("#FF3333");
        mData.add("#99FFFF");
        mData.add("#33CCCC");
        mData.add("#33FF00");
        mData.add("#99FF99");
        mData.add("#33FFFF");
        mData.add("#CCFFFF");
        mData.add("#00FF66");
        //mThemeAdapter = new ThemeAdapter(R.layout.theme_rv_item, mData);
        mThemeRv.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
        mThemeRv.setAdapter(mThemeAdapter);
        mThemeAdapter.setOnItemClickListener((baseQuickAdapter, view13, i) -> {
            //在这里发送事件通知部分控件需要修改其颜色
            SPUtils.put(getActivity(), "theme_color", mData.get(i));
            RxBus.getDefault().post("theme_color");
            dismiss();
        });

        int color = ToolsUtils.getThemeColor(getActivity());
        if (color != 0) {
            mToolbar.setBackgroundColor(color);
        }
    }

    public static SettingDialogFragment newInstance(String title) {
        SettingDialogFragment fragment = new SettingDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //dialogFragment全屏
        //setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreen);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentStyle);
        initData();
    }

    private void initData() {
        //mList = new ArrayList<>();
        ItemBean bean = new ItemBean();
        bean.setSeek(false);
        bean.setCheck(false);
        bean.setType(0);
        bean.setImage(false);
        bean.setTitle("基本设置");
        mList.add(bean);
        String[] strings = new String[]{"夜间模式", "清除缓存", "检查更新", "关于我们", "主题设置", "导航栏着色", "退出登录"};
//        if (!AppUtils.isLogin()) {
        if (!UserManager.getInstance().isLogin()) {
            strings = new String[]{"夜间模式", "清除缓存", "检查更新", "关于我们", "导航栏着色", "主题设置"};
        }
        ItemBean b = null;
        for (int i = 0; i < strings.length; i++) {
            b = new ItemBean();
            /*if (strings[i].equals("夜间模式")) {
                boolean night_mode_open = (boolean) SPUtils.get(getActivity(), "night_mode_open", false);
                b.setToggle(night_mode_open);
                b.setType(2);
            } else */
            if (strings[i].equals("清除缓存") || strings[i].equals("检查更新") || strings[i].equals("夜间模式")) {
                b.setType(3);
            } else if (strings[i].equals("关于我们") || strings[i].equals("退出登录")) {
                b.setType(1);
            } else if (strings[i].equals("主题设置")) {
                b.setType(4);
                b.setImage(true);
            } else if (strings[i].equals("导航栏着色")) {
                b.setType(2);
                boolean openNavigationBar = ToolsUtils.isOpenNavigationBar(getActivity());
                if (openNavigationBar)
                    b.setCheck(true);
                else
                    b.setCheck(false);
            }
            b.setTitle(strings[i]);
            mList.add(b);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnbinder != null)
            mUnbinder.unbind();
    }

    protected Unbinder mUnbinder;

    @OnClick(R.id.setting_iv_arrow)
    public void onViewClicked() {
        dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (ToolsUtils.getNightMode(getActivity())) {
            getDialog().getWindow().setStatusBarColor(Color.TRANSPARENT);
            getDialog().getWindow().setNavigationBarColor(Color.TRANSPARENT);
        } else {
            int color = ToolsUtils.getThemeColor(getActivity());
            if (color != 0) {
                getDialog().getWindow().setStatusBarColor(color);
            }
            if (ToolsUtils.isOpenNavigationBar(getActivity())) {
                Window window = getDialog().getWindow();
                if (ToolsUtils.getThemeColor(getActivity()) != 0)
                    window.setNavigationBarColor(ToolsUtils.getThemeColor(getActivity()));
                else
                    window.setNavigationBarColor(ToolsUtils.getAttrValue(getActivity()));
            }
        }
    }
}
